package com.spring.mvc.queue;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DispatchQueue<T> extends LinkListQueue<T> implements DispatchListener {

	private Map<String, DispatchThread> hThreads;
	private DispatchQueueProcessor<T> processor;
	
	public DispatchQueue(DispatchQueueProcessor<T> processer,int num,String desc) {
		this.processor=processer;
		
		hThreads=new HashMap<String, DispatchThread>();
		for (int i = 0; i < num; i++) {
			DispatchThread thread=new DispatchThread(i,desc);
			thread.registerListener(this);
			thread.start();
			hThreads.put(i+"", thread);
		}
	}
	
	public void process(int threadId) {
		try{
			T t=take();
			if(null != t){
				if(null != processor){
					this.processor.processQueueElement(this, t, threadId);
				}else{
					offer(t);
					Thread.yield();
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 停上运行线程
	 */
	public void dispose(){
		clear();
		Iterator<String> keys=this.hThreads.keySet().iterator();
		while(keys.hasNext()){
			String key=keys.next();
			DispatchThread dt=hThreads.get(key);
			dt.stopThread();
			dt=null;
		}
		this.hThreads.clear();
		this.hThreads=null;
	}
	
	public void putThreadAttach(String id,Object attach){
		DispatchThread dt=this.hThreads.get(id);
		if(null != dt){
			dt.setAttachment(attach);
		}
	}

}
